package com.bojx.cms.web;

import java.io.FileInputStream;
import com.bojx.cms.util.UploadUtil;
import com.jfinal.aop.Clear;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;
import com.jfinal.upload.UploadFile;

public class UEditorController extends BaseController {
	
	@Clear
	public void editor(){
		String action=getPara("action");
		if("config".equals(action)){
			forwardAction("/ueditor/config");
		}
		if("uploadimage".equals(action)){
			forwardAction("/ueditor/uploadimage");
		}
		if("uploadfile".equals(action)){
			forwardAction("/ueditor/uploadfile");
		}
	}
	
	@Clear
	public void config(){
		Record configRecord=new Record();
		configRecord.set("imageActionName", "uploadimage");
		configRecord.set("imageFieldName", "upfile");
		configRecord.set("imageMaxSize", 2048000);
		configRecord.set("imageAllowFiles",new String[]{".png", ".jpg", ".jpeg", ".gif", ".bmp"});
		configRecord.set("imageUrlPrefix", "");
		configRecord.set("fileActionName","uploadfile");
		configRecord.set("fileFieldName", "upfile");
		configRecord.set("fileMaxSize",1024*1024*1024);
		configRecord.set("fileUrlPrefix", "");
		configRecord.set("fileAllowFiles", new String[]{".png", ".jpg", ".jpeg", ".gif", ".bmp",
		        ".flv", ".swf", ".mkv", ".avi", ".rm", ".rmvb", ".mpeg", ".mpg",
		        ".ogg", ".ogv", ".mov", ".wmv", ".mp4", ".webm", ".mp3", ".wav", ".mid",
		        ".rar", ".zip", ".tar", ".gz", ".7z", ".bz2", ".cab", ".iso",
		        ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".pdf", ".txt", ".md", ".xml"});
		render(new JsonRender(configRecord).forIE()); 
	}
	
	@Clear
	public void uploadimage(){
		try{
			UploadFile uploadfile=getFile("upfile");
			String originalFileName=uploadfile.getOriginalFileName();
			String extention=originalFileName.substring(originalFileName.lastIndexOf(".")+1);
			String url=UploadUtil.uploadImage(new FileInputStream(uploadfile.getFile()), extention);
			Record record=new Record();
			record.set("title",originalFileName);
			record.set("original", originalFileName);
			record.set("state", "SUCCESS");
			record.set("url", url);
			render(new JsonRender(record).forIE());
		}catch(Exception e){
			LOG.error(e.getMessage(),e);
		}		
	}
	
	@Clear
	public void uploadfile(){
		try{
			UploadFile uploadfile=getFile("upfile");
			String originalFileName=uploadfile.getOriginalFileName();
			String extention=originalFileName.substring(originalFileName.lastIndexOf(".")+1);
			String url=UploadUtil.uploadFile(new FileInputStream(uploadfile.getFile()), extention);
			Record record=new Record();
			record.set("title",originalFileName);
			record.set("original", originalFileName);
			record.set("state", "SUCCESS");
			record.set("url", url);
			render(new JsonRender(record).forIE());
		}catch(Exception e){
			LOG.error(e.getMessage(),e);
		}
	
	}
}
